<script setup lang="ts">
import { onMounted, reactive, type PropType } from 'vue'
import type { Note, Result } from '@/stores/types'
import { useRoute, useRouter } from 'vue-router'
import * as Typeing from '@/stores/types/index'
import { getNoteById } from '@/api/notes'
import { useNoteStore } from '@/stores/modules/note'

const state = reactive({
  note: {
    content: '',
    dates: ''
  },
  id: '',
  oldContent: ''
})
const router = useRouter()
const route = useRoute()
const date = new Date()
const { notes, addNote, updateNote, deleteNote } = useNoteStore()

// 点击返回提交数据(存在id为更新，并且如果存在id，内容修改为空则为删除，不存在id为添加)
const onClickLeft = async () => {
  if (!state.note.content.trim()) {
    if (state.id) {
      // 删除
      await deleteNote(state.id)
    }
    router.go(-1)
    return
  }
  state.note.dates = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  if (state.id) {
    if (state.oldContent !== state.note.content) {
      // 更新
      await updateNote({
        id: state.id,
        note: state.note
      })
    }
  } else {
    // 添加
    await addNote(state.note)
  }
  router.go(-1)
}
const initNote = () => {
  const id = route.query.id
  if (!id) return
  const note = notes!.find((item) => item._id === id)
  if (note) {
    state.note.content = note.content
    state.oldContent = note.content
    state.id = note._id!
  } else {
    getNoteById<Result<Note>>(id as string).then((data) => {
      // todo
      console.log(data)
    })
  }
}
onMounted(() => {
  initNote()
})
</script>

<template>
  <div class="add-note-box">
    <van-nav-bar left-arrow @click-left="onClickLeft">
      <template #right>
        <van-icon name="success" size="18" />
      </template>
    </van-nav-bar>
    <van-field
      class="field"
      v-model="state.note.content"
      rows="1"
      autosize
      type="textarea"
      placeholder="请输入内容"
    />
  </div>
</template>

<style lang="scss" scoped>
.add-note-box {
  width: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  flex: 1;
  background-color: #fff;
}
.field {
  font-size: 0.22rem;
}
</style>
